package com.ungao.tools.generator.connection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class DbConnection extends AbstractConnection {

    public DbConnection(Connection connection) throws Exception {
        super(connection);
    }

    public DbConnection(String url, String username, String password, String driver) throws Exception {
        super(url, username, password, driver);
    }

    /**
     * 获取表结果集
     *
     * @param tableName
     * @return
     */
    @Override
    public ResultSet tables(String tableName) {
        ResultSet resultSet = null;
        try {
            resultSet = this.connection.getMetaData().getTables(this.connection.getCatalog(), "%", tableName, new String[]{"TABLE"});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultSet;
    }

    /**
     * 获取主键结果集
     *
     * @param tableName
     * @return
     */
    @Override
    public ResultSet primaries(String tableName) {
        ResultSet resultSet = null;
        try {
            resultSet = this.connection.getMetaData().getPrimaryKeys(this.connection.getCatalog(), "%", tableName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultSet;
    }

    /**
     * 获取字段结果集
     *
     * @param tableName
     * @return
     * @throws Exception
     */
    @Override
    public ResultSet columns(String tableName) {
        ResultSet resultSet = null;
        try {
            resultSet = this.connection.getMetaData().getColumns(this.connection.getCatalog(), "%", tableName, "%");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultSet;
    }

    /**
     * 获取列详细信息
     *
     * @param tableName
     * @return
     */
    @Override
    public ResultSetMetaData info(String tableName) {
        ResultSetMetaData resultSetMetaData = null;
        try {
            PreparedStatement statement = this.connection.prepareStatement(String.format("SELECT * FROM %s", tableName));
            resultSetMetaData = statement.executeQuery().getMetaData();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultSetMetaData;
    }

}
